package com.jiyun.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiyun.model.user.YlUser;
import com.jiyun.result.Result;
import com.jiyun.service.IYlUserService;
import com.jiyun.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * APP用户信息表 前端控制器
 * </p>
 *
 * @author 
 * @since 2024-09-20
 */
@RestController
@RequestMapping("/user/")
@Slf4j
@Api("登录模块")
public class YlUserController {

    @Autowired
    private IYlUserService ylUserService;


    @ApiModelProperty("账号密码登录")
    @RequestMapping("login")
    public Result login(@RequestBody YlUser user) {
        return ylUserService.login(user);
    }

    @ApiModelProperty("手机号登录")
    @RequestMapping("phoneLogin")
    public Result phoneLogin(@RequestBody YlUser user) {
        YlUser ylUser = ylUserService.getOne(new QueryWrapper<YlUser>().eq("phone", user.getPhone()));
        return aa(ylUser);
    }
    @ApiModelProperty("手机号登录生成验证码")
    @RequestMapping("getYzm")
    private Result getYzm() {
        Random random = new Random();
        // 生成一个范围在 [1000, 9999] 之间的随机数
        int yzm = random.nextInt(9000) + 1000;
        return Result.ok(yzm);
    }


    private Result<Map> aa(YlUser user){
        //        生成token
        String token = AppJwtUtil.getToken(user.getId());
//        返回：token user
        Map data = new HashMap();
        data.put("user",user.getName());
        data.put("token",token);
        return Result.ok(data);
    }





//    拿到token，返回user
    @RequestMapping("getUser/{token}")
    public Result getUser(@PathVariable String token) {
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //4.1、获取id
        Integer id = (Integer)claims.get("id");
        log.info("id是："+id);
        YlUser user = ylUserService.getById(id);
        log.info("user："+user);
        return Result.ok(user);
    }


    //token测试接口
    @RequestMapping("bb/{token}")
    public YlUser bb(@PathVariable String token){
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //4.1、获取id
        Integer id = (Integer)claims.get("id");
        log.info("id是："+id);
        YlUser byId = ylUserService.getById(id);
        log.info("user："+byId);
        return byId;
    }

    @RequestMapping("cc")
    public String cc(){
        return "委托人的共和国法人实体的规范化却认为特意如何发掘古墓";
    }


}
